#include "my_stdio.h"

mFILE* mfopen(const char* filename,const char* mode)
{
    int fd = -1;
    if (my_strcmp(mode,"w") == 0)
    {
        fd = open(filename,O_WRONLY | O_CREAT | O_TRUNC,0666);
        if (fd < 0) return NULL;
    }   
    else if (my_strcmp(mode,"a") == 0)
    {
        fd = open(filename,O_WRONLY | O_CREAT | O_APPEND,0666);
        if (fd < 0) return NULL;
    }   
    else if (my_strcmp(mode,"r") == 0)
    {
        fd = open(filename,O_RDONLY);
        if (fd < 0) return NULL;
    }   
    mFILE* pf = (mFILE*)malloc(sizeof(mFILE)); 
    pf->fileno = fd;
    pf->size = 0;
    pf->cap = basesize;
    pf->flg = FFLUSH_LINE;
    return pf;
}
void mfflush(mFILE* pf)
{
   write(pf->fileno,pf->buffer,pf->size);
   pf->size = 0;
}
void mfclose(mFILE* pf)
{
    if (pf->size > 0) mfflush(pf);
    pf->size = 0; //清理
    free(pf);
}
int mfwrite(const void* filename,int num,mFILE* pf)
{
    if (filename == NULL) return -1;
    if (pf->size + num > pf->cap) //如果缓冲区装不下了先刷新
    {
        mfflush(pf);
    }
    memcpy(pf->buffer+pf->size,filename,num);   
    pf->size += num; 
    if (pf->size > 0 && pf->buffer[my_strlen(pf->buffer)-1] == '\n' && 
            pf->flg == FFLUSH_LINE) 
    {
        mfflush(pf);
    }
    return num;
}
